package com.other.springbootconfigureorder.data;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Component
public class ExcelReader {

    public List<List<String>> readExcelData(String sheetName) throws Exception {
        InputStream inputStream = new ClassPathResource("data/光束配置关系.xlsx").getInputStream();
        Workbook workbook = new XSSFWorkbook(inputStream);

        // 获取"配置表"工作表
        Sheet sheet = workbook.getSheet(sheetName);
        Iterator<Row> rowIterator = sheet.iterator();

        List<List<String>> rowDataList = new ArrayList<>();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();

            List<String> cellDataList = new ArrayList<>();

            // 这里我们假设每一行都有7个单元格（A~G）
            for (int i = 0; i < 7; i++) {
                if (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    String cellValue = getCellValueAsString(cell);
                    cellDataList.add(cellValue);
                }
            }

            // 将获取到的每一行数据添加到列表中
            rowDataList.add(cellDataList);
        }

        workbook.close();
        inputStream.close();

        return rowDataList;
    }

    private String getCellValueAsString(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}